import os
import logging

import json
from config import GlobalContextData

COLOR_CODES = {
    'DEBUG': '\033[94m',  # 蓝色
    'INFO': '\033[92m',   # 绿色
    'WARNING': '\033[93m',# 黄色
    'ERROR': '\033[91m',  # 红色
    'CRITICAL': '\033[1;41m',  # 背景红色
    'RESET': '\033[0m'    # 重置颜色
}

MAX_CACHE_SIZE = 5 * 1024 * 1024  # 5MB
log_file_path = GlobalContextData.LogPath
log_dir = log_file_path.parent
if not log_dir.is_dir():
    log_dir.mkdir(parents=True)

def count_files_in_directory() -> int:
    if not log_dir.is_dir():
        log_dir.mkdir(parents=True)

    file_count = sum(1 for entry in log_dir.iterdir() if entry.is_file())
    return file_count


def parse_log_content(value):
    try:
        return str(value)
    except Exception:
        print(f'{type(value)} not parse.')
        return None

def write_log_to_log_file(obj: dict):
    log_console_path = log_dir / f'{log_file_path.stem}.console{log_file_path.suffix}'

    log_contents = json.dumps(obj, default=parse_log_content) + '\n'
    console_contents = obj['console'] + '\n'

    for path, content in [(log_file_path, log_contents), (log_console_path, console_contents)]:
        with path.open("a", encoding="utf-8") as f:
            f.write(content)

        try:
            if path.stat().st_size >= MAX_CACHE_SIZE:
                base, ext = os.path.splitext(path)
                renamed_path = f"{base}_{count_files_in_directory() - 1}{ext}"
                os.rename(path, renamed_path)
        except Exception as ex:
            print(ex)

class JSONFormatter(logging.Formatter):
    def format(self, record):
        # 准备日志内容的字典
        log_record = {
            'time': self.formatTime(record, self.datefmt),
            'level': record.levelname,
            'message': record.getMessage(),
            'pathname': record.pathname,
            'lineno': record.lineno,
            'funcName': record.funcName,
            'exc_info': record.exc_info,
            'exc_text': record.exc_text,
            'env': 'debug' if GlobalContextData.Debug else 'prod',
            'console': f"{self.formatTime(record, self.datefmt)} - {record.levelname} - "
                       f"{record.pathname}:{record.lineno} - {record.getMessage()}"
        }

        # 添加额外信息（如果有）
        extra_fields = ['method', 'path', 'user', 'action', 'token', 'payload', 'header', 'query', 'auth']
        for extra_field in extra_fields:
            if hasattr(record, extra_field):
                log_record[extra_field] = getattr(record, extra_field)

        return log_record

class JSONLogHandler(logging.Handler):
    def __init__(self):
        super().__init__()
        self.formatter = JSONFormatter()

    def emit(self, record):
        try:
            data = self.format(record)
            if GlobalContextData.Debug:
                level = record.levelname
                color = COLOR_CODES.get(level, COLOR_CODES['RESET'])
                print(f"{color}{data['console']}{COLOR_CODES['RESET']}")

            write_log_to_log_file(data)
            # to do, upload to log cloud
        except Exception :
            pass